package com.mmp.main.servlet.joborder;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.entity.Employee;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.entity.LookupJobOrderPriority;
import com.mmp.main.entity.LookupJobOrderType;
import com.mmp.main.util.Default;
import com.mmp.main.util.Enums;

public class JobOrderOpenDisplayServlet extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("jobOrderTypes", dbQueryManager.findAll(LookupJobOrderType.class));
		request.setAttribute("jobOrderPriorities", dbQueryManager.findAll(LookupJobOrderPriority.class));

		int siteId = getSessionSiteId(request);

		request.setAttribute("autoGeneratedJobOrderNo", generateNewJobOrderNo(siteId));

		request.setAttribute(
				"responsibleEngs",
				dbQueryManager.getEmployees(siteId, new Enums.USER_TYPE[] { Enums.USER_TYPE.BIOMEDICAL_ENGINEER,
						Enums.USER_TYPE.BIOMEDICAL_TECHNICIAN }, false));

		Employee hospDepHead = ((HospitalDevice) request.getAttribute(Default.DEVICE_INFO_ATTR_NAME))
				.getHospitalDepartment().getDepartmentHead();
		request.setAttribute("hospDepHead", hospDepHead);

		request.setAttribute("biomedDepHead",
				dbQueryManager.getEmployees(siteId, Enums.USER_TYPE.BIOMEDICAL_DEPARTMENT_HEAD, false).get(0));
		
		forward(request, response, "joborder/JobOrderOpen.jsp");
	}

	// concurrency not handled properly
	private String generateNewJobOrderNo(int siteId) {
		Date now = new Date();
		String yy = new SimpleDateFormat("yy").format(now);
		String mm = new SimpleDateFormat("MM").format(now);
		long serial = dbQueryManager.getJobOrderCount(siteId, Integer.parseInt(mm), Integer.parseInt("20" + yy)) + 1;
		// return "" + siteId + (Long.parseLong(yy + mm) * 1000 + serial);
		return "" + (Long.parseLong(yy + mm) * 1000 + serial);
	}

}
